import { defineStore } from 'pinia'
import { useUserStore, usePermissionStore, useTabStore, useSeekerStore, useRecruiterStore } from '@/store'
import { resetRouter, router } from '@/router'
import { lStorage } from '@/utils';

export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: undefined,
    hasName: undefined,
    role: undefined,
  }),
  actions: {
    setToken(accessToken) {
      this.accessToken = accessToken
      lStorage.set('token', accessToken)
    },
    setHasName(hasname) {
      this.hasName = hasname
      lStorage.set('hasName', hasname)
    },
    setRole(role) {
      this.role = role
      lStorage.set('role', role)
    },
    resetToken() {
      this.$reset()
      lStorage.remove('token')
      lStorage.remove('hasName')
      lStorage.remove('role')
    },
    toLogin() {
      const currentRoute = unref(router.currentRoute)
      router.replace({
        path: '/login',
        query: currentRoute.query,
      })
    },
    resetLoginState() {
      const { resetUser } = useUserStore()
      const { resetPermission } = usePermissionStore()
      const { resetTabs } = useTabStore()
      const { resetSeeker } = useSeekerStore()
      const { resetRecruiter } = useRecruiterStore()
      // 重置用户
      resetUser()
      // 重置权限
      resetPermission()
      // 重置Tabs
      resetTabs()
      // 重置路由
      resetRouter()
      // 重置求职者
      resetSeeker()
      // 重置招聘方
      resetRecruiter()
      // 重置token
      this.resetToken()
    },
    async logout() {
      this.resetLoginState()
      this.toLogin()
    },
  },
  persist: {
    key: 'auth',
  },
})
